package com.vchello.controller.upload;

import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Iterator;

import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.vchello.bean.file.File;
import com.vchello.controller.BaseController;
import com.vchello.service.file.FileService;
import com.vchello.util.ToolUtil;
import com.vchello.util.UploadFileHelper;
import com.vchello.util.Utility;

import net.sf.json.JSONObject;

/**
 * 
 * @author power
 *
 */
@Controller
@RequestMapping("/uploadFile")
public class UploadFileController extends BaseController {

	private final static int fileFileMaxLength = 50 * 1024 * 1024; //文件的最大值
	private final static int picFileMaxLength = 5 * 1024 * 1024; // 图片文件的最大值
	
	@Autowired
	private FileService fileService;
	
	
	/**
	 * 截取投资人头像
	 * @param x
	 * @param y
	 * @param width
	 * @param height
	 * @param url
	 */
	@RequestMapping(value="/cutLogo", method = RequestMethod.POST)
	public void cutLogo(int x, int y, int width, int height, String url){
		try {
			if(width ==0 || height == 0 || (!StringUtils.isNotBlank(url))){
				error("参数错误");
				return;
			}
			String path = request.getSession().getServletContext().getRealPath("/")+StringEscapeUtils.unescapeHtml4(url);
			java.io.File file = new java.io.File(path);
			if(file.exists() && file.isFile()){
				String urlpath = cutImage(file, x, y, width, height,path,url);
				if(StringUtils.isNotBlank(urlpath)){
					success(StringEscapeUtils.unescapeHtml4(urlpath));
				}
			}else{
				error("文件不存在");
			}
		} catch (Exception e) {
			e.printStackTrace();
			error("剪切出错,文件可能有损坏");
		}
	}
	
	@RequestMapping("/file")
	public void uploadFile(@RequestParam MultipartFile[] uploadFolderFile, File file){
		try {
			// 文件类型:btnFile[0].getContentType()
			// 文件名称:btnFile[0].getName()
			if (uploadFolderFile != null && uploadFolderFile.length == 1) {
				String fileName = uploadFolderFile[0].getOriginalFilename();
				float fileSize = (float) uploadFolderFile[0].getSize() / 1024;
				if (checkFile(fileName, uploadFolderFile[0].getSize())) {
					String path = UploadFileHelper.uploadFolderTempFile(uploadFolderFile[0], fileName, request);
					if (StringUtils.isNotBlank(path)) {
						boolean isTrue = false;
						file.setCreateTime(Utility.getSimpleFormatedDayNow());
						file.setUrl(path);
						file.setOriginalName(fileName);
						file.setName(getSplitFileName(fileName));
						file.setUrl(path);
						file.setSize(fileSize);
						isTrue = fileService.insertOrUpdate(file);
						if(isTrue) {
							success(getFileJson(file));
						}
					} else {
						error("上传失败！");
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			error("上传失败！");
		}
	}

	/**
	 * 上传图片
	 * @param imageFile
	 * @param request
	 * @param response
	 */
	@RequestMapping("/img")
	public void uploadImage(@RequestParam MultipartFile[] imageFile, HttpServletRequest request,
			HttpServletResponse response) {
		try {
			if (imageFile[0].getSize() > Integer.MAX_VALUE) {// 文件长度
				System.out.println(imageFile[0]);
			}
			if (imageFile != null && imageFile.length == 1) {
				String fileName = imageFile[0].getOriginalFilename();
				if (checkPicFile(fileName, imageFile[0].getSize())) {
					String path = UploadFileHelper.uploadTempFile(imageFile[0], fileName, request);
					if (StringUtils.isNotBlank(path)) {
						errorValue(getJsonObj(path));
					} else {
						error("上传失败！");
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			error("上传失败！");
		}
	}
	
	/**
	 * 上传bp
	 * @param imageFile
	 * @param request
	 * @param response
	 */
	@RequestMapping("/bp")
	public void uploadBP(@RequestParam MultipartFile[] bpFile, HttpServletRequest request,
			HttpServletResponse response) {
		try {
			if (bpFile[0].getSize() > Integer.MAX_VALUE) {// 文件长度
				System.out.println(bpFile[0]);
			}
			if (bpFile != null && bpFile.length == 1) {
				String fileName = bpFile[0].getOriginalFilename();
				if (checkBPFile(fileName, bpFile[0].getSize())) {
					String path = UploadFileHelper.uploadTempFile(bpFile[0], fileName, request);
					if (StringUtils.isNotBlank(path)) {
						errorValue(getJsonObj(path));
					} else {
						error("上传失败！");
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			error("上传失败！");
		}
	}
	
	private String getSplitFileName(String fileName){
		if(ToolUtil.isNotEmpty(fileName)) {
			int index = fileName.lastIndexOf(".");
			return fileName.substring(0, index);
		}
		return null;
	}

	/**
	 * 文件管理验证
	 * @param proImgFileName
	 * @param file
	 * @return
	 * @throws IOException
	 */
	public boolean checkFile(String fileName, long fileSize) throws IOException {
		if (fileName == null) {
			error("");
			return false;
		}
		if (Utility.checkFile(fileName)) {
			if (fileSize > fileFileMaxLength) {
				error("文件不能超过50M!");
				return false;
			}
		} else {
			error("文件格式错误!");
			return false;
		}
		return true;
	}
	
	/**
	 * 一般图片验证
	 * 
	 * @param proImgFileName
	 * @param file
	 * @return
	 * @throws IOException
	 */
	public boolean checkPicFile(String fileName, long fileSize) throws IOException {
		if (fileName == null) {
			error("");
			return false;
		}
		if (Utility.checkPic(fileName)) {
			if (fileSize > picFileMaxLength) {
				error("图片不能超过5M!");
				return false;
			}
		} else {
			error("图片格式错误!");
			return false;
		}
		return true;
	}
	
	/**
	 * 商机计划书检验
	 * @param proImgFileName
	 * @param file
	 * @return
	 * @throws IOException
	 */
	public boolean checkBPFile(String fileName, long fileSize) throws IOException {
		if (fileName == null) {
			error("");
			return false;
		}
		if (Utility.checkBPFile(fileName)) {
			if (fileSize > fileFileMaxLength) {
				error("文件不能超过50M!");
				return false;
			}
		} else {
			error("文件格式错误!");
			return false;
		}
		return true;
	}
	
	private String getJsonObj(String path) {
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("uploadFile", path);
		jsonObject.put("status", true);
		return jsonObject.toString();
	}
	
	/**
     * 截图
     * @param img
     * @param x
     * @param y
     * @param width
     * @param height
     * @return
     */
    public String cutImage(java.io.File file, int x, int y, int width, int height, String path, String url) {
    	String newPath = "";
        try {
        	int index = file.getName().lastIndexOf(".");
        	if(index == -1)
        		return "";
        	String endPath = file.getName().substring(index+1);
        	Iterator<ImageReader> it = ImageIO.getImageReadersByFormatName(endPath);
        	ImageReader reader = it.next();
        	// 获取图片流
        	ImageInputStream  iis = ImageIO.createImageInputStream(file);
        	reader.setInput(iis, true);
        	ImageReadParam param = reader.getDefaultReadParam();
            /*
             * 图片裁剪区域。Rectangle 指定了坐标空间中的一个区域，通过 Rectangle 对象
             * 的左上顶点的坐标（x，y）、宽度和高度可以定义这个区域。
             */
            Rectangle rect = new Rectangle(x, y, width, height);
            // 提供一个 BufferedImage，将其用作解码像素数据的目标。
            param.setSourceRegion(rect);
            /*
             * 使用所提供的 ImageReadParam 读取通过索引 imageIndex 指定的对象，并将 它作为一个完整的
             * BufferedImage 返回。
             */
            BufferedImage bi = reader.read(0, param);
            // 保存新图片
            newPath = path+"."+endPath;
            ImageIO.write(bi, endPath, new java.io.File(newPath));
            newPath = url +"."+endPath;
        } catch (Exception e) {
            e.printStackTrace();
            error("图片格式有损，无法截图");
        }
        return newPath;
    }
	
	private String getFileJson(File file){
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("name", file.getName());
		jsonObject.put("size", file.getSize());
		jsonObject.put("createTime", file.getCreateTime());
		jsonObject.put("id", file.getId());
		jsonObject.put("uploadFile", "");
		jsonObject.put("status", true);
		return jsonObject.toString();
	}
}
